<template>
  <div class="home-container">
    <Header />
    <div class="weather-display" v-if="currentWeather && forecastWeather">
      <div class="current-weather">
        <h3>当前天气 - {{ currentWeather.lives[0].city }} 更新时间：{{ currentWeather.lives[0].reporttime }}</h3>
        <div class="weather-info">
          <p>天气: {{ currentWeather.lives[0].weather }}</p>
          <p>温度: {{ currentWeather.lives[0].temperature }}°C</p>
          <p>湿度: {{ currentWeather.lives[0].humidity }}%</p>
          <p>风向: {{ currentWeather.lives[0].winddirection }} {{ currentWeather.lives[0].windpower }}级</p>
        </div>
      </div>
      <div class="forecast-chart" ref="chartRef"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, onUnmounted, computed } from 'vue';
  import * as echarts from 'echarts';
  import type { WeatherResponseType, WeatherCastType, GeocodeResponseType, IpLocationResponseType } from '@/types/gmap';
  import { getWeather, getIpLocation, getGeocode } from '@/api/gmap.ts';
  import Header from '@/components/Header.vue';

  const currentWeather = ref<WeatherResponseType | null>(null);
  const forecastWeather = ref<WeatherResponseType | null>(null);
  const locationData = ref<IpLocationResponseType | null>(null);
  const geocodeData = ref<GeocodeResponseType['geocodes'][0] | null>(null);

  const chartRef = ref<HTMLElement>();
  let chart: echarts.ECharts | null = null;

  //省市 拼接 方便查询地理/逆地理编码
  const fullAddress = computed(() => {
    if (!locationData.value) return '';
    return `${locationData.value.province}${locationData.value.city}`;
  });

  // 获取天气数据
  const fetchWeatherData = async () => {
    try {
      const location = await getIpLocation();
      console.log(location);
      locationData.value = location;

      const res = await getGeocode(fullAddress.value);//这里不能直接写fullAddress 这是一个ref对象不是值
      console.log(res);
      geocodeData.value = res.geocodes[0]; // 获取第一个结果（南京市）
      const adcode = res.geocodes[0].adcode;

      currentWeather.value = await getWeather(adcode);
      forecastWeather.value = await getWeather(adcode, 'all');

      // 延迟渲染图表，确保DOM已更新
      setTimeout(renderChart, 0);
    } catch (error) {
      console.error('获取天气数据失败:', error);
    }
  };

  const renderChart = () => {
    if (!chartRef.value || !forecastWeather.value || !forecastWeather.value.forecasts) return;

    if (chart) {
      chart.dispose();
    }

    chart = echarts.init(chartRef.value);
    const forecasts = forecastWeather.value.forecasts[0].casts.slice(0, 4); // 取未来三天
    const dates = forecasts.map((item: WeatherCastType) => item.date);
    const dayTemps = forecasts.map((item: WeatherCastType) => parseInt(item.daytemp));
    const nightTemps = forecasts.map((item: WeatherCastType) => parseInt(item.nighttemp));

    const option = {
      title: {
        text: '未来三天天气预报',
        left: 'center',
      },
      tooltip: {
        trigger: 'axis',
        formatter: function(params: any) {
          const data = params[0];
          const index = data.dataIndex;
          const forecast = forecasts[index];
          return `
                ${forecast.date} 星期${forecast.week}<br/>
                白天: ${forecast.dayweather} ${forecast.daytemp}°C<br/>
                夜间: ${forecast.nightweather} ${forecast.nighttemp}°C<br/>
                白天风向: ${forecast.daywind} ${forecast.daypower}级<br/>
                夜间风向: ${forecast.nightwind} ${forecast.nightpower}级
                `;
        },
      },
      legend: {
        data: ['白天温度', '夜间温度'],
        top: '10%',
      },
      xAxis: {
        type: 'category',
        data: dates,
      },
      yAxis: {
        type: 'value',
        name: '温度 (°C)',
      },
      series: [
        {
          name: '白天温度',
          type: 'line',
          data: dayTemps,
          symbol: 'circle',
          symbolSize: 8,
          itemStyle: {
            color: '#b3ff6b',
            borderColor: '#b3ff6b',
            borderWidth: 2,
          },
          lineStyle: {
            color: '#b3ff6b',
            width: 2,
          },
        },
        {
          name: '夜间温度',
          type: 'line',
          data: nightTemps,
          symbol: 'circle',
          symbolSize: 8,
          itemStyle: {
            color: '#0c0c0c',
            borderColor: '#0c0c0c',
            borderWidth: 2,
          },
          lineStyle: {
            color: '#0c0c0c',
            width: 2,
          },
        },
      ],
    };

    chart.setOption(option);
  };

  onMounted(() => {
    fetchWeatherData();

    // 监听窗口大小变化，重新渲染图表
    window.addEventListener('resize', () => {
      chart?.resize();
    });
  });

  onUnmounted(() => {
    if (chart) {
      chart.dispose();
    }
    window.removeEventListener('resize', () => {
      chart?.resize();
    });
  });
</script>

<style scoped>
  .home-container {
    width: 100%;
    height: 100%;
    padding: 20px;
    display: flex;
    flex-direction: column;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    gap: 20px;
    overflow: hidden; /* 防止内容溢出导致滚动条 */
    box-sizing: border-box; /* 确保padding包含在宽度内 */
  }

  .weather-display {
    width: 100%;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    flex: 1;
    overflow: hidden; /* 防止内容溢出 */
    box-sizing: border-box; /* 确保padding包含在宽度内 */
  }

  .current-weather {
    margin-bottom: 20px;
  }

  .current-weather h3 {
    margin-bottom: 10px;
    color: #333;
  }

  .weather-info {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
    gap: 10px;
  }

  .weather-info p {
    margin: 0;
    color: #666;
  }

  .forecast-chart {
    width: 100%;
    height: 400px;
    overflow: hidden; /* 防止图表溢出 */
  }
</style>
